#!/usr/bin/python3
#-*- coding=utf-8 -*-

import os
import socket
import json
import struct
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import sys
import subprocess
import tarfile

LOG_PATH = "/data/log"
PROCESSING = "/tmp/oss_log"
OSS_FILE = "world_oss*"
TAR_FILE = r'/tmp/world_oss_%s.tar.gz'
OSS_TYPE = ['PlayerOnline', 
            'PlayerRegister',
            'PlayerLogin',
            'PlayerLogout',
            'PlayerSetting',
            'MoneyFlow',
            'AttributeFlow',
            'ItemFlow',
            'TankFlow',
            'ComponentFlow',
            'PaintingFlow',
            'EquipFlow',
            'AmmoFlow',
            'VipFlow',
            'PlayerUseComponent',
            'PlayerFps',
            'PlayerJoinQueue',
            'PlayerQuitQueue',
            'PlayerStartGame',
            'PlayerEndGame',
            'PlayerQuitGame',
            'AttackAction',
            'PlayerGuide',
            'PlayerUI',
            'PlayerShare',
            'PlayerApplyPainting',
            'PlayerSwitchAmmo',
            'AutoLock']

#SENDER = 'david_xcy@163.com'
SENDER = '191130863@qq.com'
RECEIVER = ['191130863@qq.com','miaozhuo@thinkygame.com']
#RECEIVER = ['191130863@qq.com', 'david_xcy@163.com']
SUBJECT = r'%s 游戏用户统计'
#SMTPSERVER = 'smtp.163.com'
SMTPSERVER = 'smtp.qq.com'
SMTPPORT = 465
#MAIL_PASSWORD = 'flzx6qc'
MAIL_PASSWORD = 'rvnysuxjltirbhia'


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
    			s.fileno(),
    			0x8915, # SIOCGIFADDR
    			struct.pack('256s', ifname[:15])
    			)[20:24])
def conn_info():
    cmd = "netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
    status, output = subprocess.getstatusoutput(cmd)
    if status != 0:
    	return None
    output = output.split('\n')
    result = dict()
    for data in output:
        temp = data.split()
        result[temp[0]] = temp[1]
    return result

def send_mail(title, send_str, files):
    msg = MIMEMultipart()
    msg['Subject'] = Header(title, 'utf-8')
    msg['From'] = 'server<%s>' %SENDER
    msg['To'] = ';'.join(RECEIVER)
    msg.attach(MIMEText(send_str, 'plain', 'utf-8'))
    
    #add attachment
    for path in files:
        if not os.path.isfile(path):
            continue
        attachment = MIMEApplication(open(path, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='{0}'.format(os.path.basename(path)))
        msg.attach(attachment)
        os.remove(path)
    	
    try:
        #smtp = smtplib.SMTP()
        #smtp.connect(SMTPSERVER)
        smtp = smtplib.SMTP_SSL(SMTPSERVER, SMTPPORT)
        smtp.login(SENDER, MAIL_PASSWORD)
        smtp.sendmail(SENDER, RECEIVER, msg.as_string())
    except Exception as e:
        print("send mail to %s error!" % ";".join(RECEIVER))
        print(e)
    smtp.quit()

def tar(filelist, path_name):
    tf = tarfile.open(path_name, "w:gz")
    
    for file_name in filelist:
        tf.add(file_name)
    
    tf.close()

def collect_oss_file(files, path_name):
    processing_path = os.path.join(PROCESSING, time.strftime("%Y%m%d", time.localtime(time.time() - 86400)))
    if not os.path.exists(processing_path):
        cmd = '''mkdir -p %s''' %processing_path
        status, output= subprocess.getstatusoutput(cmd)
        if status != 0:
            return

    for elem in OSS_TYPE:
        file_name = os.path.join(processing_path, "%s.txt" %elem)
        cmd = '''grep "{0}" {1} > {2}'''.format(elem, path_name, file_name)
        status, output= subprocess.getstatusoutput(cmd)
        if status == 0:
            files.append(file_name)

#    cmd = 'find %s -name \"%s*\"' %(path_name, OSS_FILE)
#    status, output = subprocess.getstatusoutput(cmd)
#    if status == 0:
#        output = output.split('\n')
#        for 



def main():
    time_now = time.strftime("%Y%m%d", time.localtime(time.time() - 86400))
    log_path = os.path.join(LOG_PATH, "%s/*/world_oss*" %time_now)
    print(log_path , LOG_PATH)
    cmd = '''grep "PlayerLogin" %s | awk -F "|" '!a[$7]++{print $7}' | wc -l''' %log_path
    login_count = -1
    status, output= subprocess.getstatusoutput(cmd)
    print(output, "---1-----------")
    if status != 0:
        login_count = -1
    else:
        login_count = output

    cmd = '''grep -i "register" %s | awk -F "|" '!a[$7]++{print $7}' | wc -l''' %log_path 
    register_count = -1
    status, output= subprocess.getstatusoutput(cmd)
    print(output, "----2----------")
    if status != 0:
        register_count = -1
    else:
        register_count = output
    stay_count = int(login_count) - int(register_count)
    print(login_count, register_count, stay_count, 'asdf')
    
    files = list()
    collect_oss_file(files, log_path):

    cmd = 'find %s -name \"%s*\"' %(log_path, OSS_FILE)
    status, output = subprocess.getstatusoutput(cmd)
    if status == 0:
        output = output.split('\n')
        file_name = TAR_FILE %time.strftime("%Y%m%d ", time.localtime(time.time() - 86400))
        tar(output, file_name)
        files.append(file_name)

    send_mail(SUBJECT %time.strftime("%Y/%m/%d ", time.localtime(time.time() - 86400)), "用户登入数：%s\n用户注册数：%s\n用户留存数：%s\n" %(login_count,register_count, stay_count), files)
    

if __name__ == "__main__":
    main()
